import React from 'react';
import routes from './routes';
import {getDetail} from './api';
import styles from './style.css';
import {injectIntl} from './intl';
import PropTypes from 'prop-types';
import Return from '../common/Return';
import {PERMISSION} from './constants';
import {hasPermissions} from './utils';
import {newOrUpdateValidator} from './validator';
import TextInput from 'Shared/components/TextInput';
import WrappedDatePicker from '../common/WrappedDatePicker';
import SaleShipmentSelectPanel from './SaleShipmentSelectPanel';
import {FORM_OPTIONS, TABLE, FIXED_COLUMN_WIDTH} from '../constants';
import {Spin, Popconfirm, Card, Button, Row, Col, Table, Form} from 'antd';
class NewPanel extends React.PureComponent {
    state = {
        loading: false,
        hasOperat: false,
        data: {},
        showSaleShipmentSelectPanel: false,
        details: []
    }
    componentDidMount() {
        if(this.props.id) {
            this.setState({loading: true});
            getDetail(this.props.id)
                .then(res => {
                    if(res.ok)
                        this.setState({
                            loading: false,
                            data: res.data,
                            details: res.data.details
                        });
                    else
                        this.setState(({
                            loading: false
                        }));
                });
        }
    }
    componentWillUnmount() {
        this.isunmount = true;
    }
    onChange = (value, name) => {
        const data = Object.assign({}, this.state.data, {
            [name]: value
        });
        this.setState({
            data,
            hasOperat: true
        });
    }
    // 增加清单
    onClickAddDetailBtn = () => {
        this.setState({
            showSaleShipmentSelectPanel: !this.state.showSaleShipmentSelectPanel
        });
    }
    onSelectSaleShipmentLists = value => {
        const {details} = this.state;
        value.map(p => {
            const index = details.findIndex(d => d.saleShipmentCode === p.code);
            if(index === -1) {
                const detail = {
                    saleShipmentCode: p.code,
                    batchNumber: p.batchNumber,
                };
                details.push(detail);
            }
            return p;
        });
        this.setState({
            showSaleShipmentSelectPanel: false,
            hasOperat: true,
            details
        });
    }
    
    onClickOkOnPopconfirm = () => {
        this.props.onCancel();
    }
    onSubmit = () => {
        const {data, details} = this.state;
        const isValid = newOrUpdateValidator(data, details);
        if(!isValid) {
            this.setState({
                validate: true
            });
            return;
        }
        this.setState({loading: true});
        this.props.onSubmit(data, details).then(res => {
            if(res.success)
                this.props.successReturn();
            if(!this.isunmount)
                this.setState({loading: false});
        });
    }
    onDeleteAll = () => {
        this.setState({
            details: [],
            hasOperat: true
        });
    }
    onDeleteDetail = e => {
        const id = e.target.dataset.id;
        const details = this.state.details.filter(p => p.id !== id);
        this.setState({
            details,
            hasOperat: true
        });
    }
    render() {
        const {formatMessage} = this.props.intl;
        const {data, details, loading} = this.state;
        const validateBoardDate = !data.boardDate && this.state.validate ? 'error' : null;
        const validateBoardPort = !data.boardPort && this.state.validate ? 'error' : null;
        const validateDestinationPort = !data.destinationPort && this.state.validate ? 'error' : null;
        const validateCarrierName = !data.carrierName && this.state.validate ? 'error' : null;
        const validatePlanArriveTime = !data.planArriveTime && this.state.validate ? 'error' : null;
        const submitable = !hasPermissions(PERMISSION.add, this.props.permissions) || !hasPermissions(PERMISSION.update, this.props.permissions);
        
        const colums = [{
            title: formatMessage({
                id: 'newPanel.column.saleShipmentCode',
                defaultMessage: '发运单号'
            }),
            dataIndex: 'saleShipmentCode',
        }, {
            title: formatMessage({
                id: 'newPanel.column.batchNumber',
                defaultMessage: '批次号'
            }),
            dataIndex: 'batchNumber',
        }, {
            title: details.length > 0
                ? (
                    <Popconfirm placement="topRight" title={formatMessage({
                        id: 'newPanel.validation.isDelete',
                        defaultMessage: '是否确认全部删除？'
                    })} onConfirm={this.onDeleteAll} >
                        <a>{formatMessage({
                            id: 'newPanel.validation.clear',
                            defaultMessage: '清空'
                        })}</a>
                    </Popconfirm>
                )
                : null,
            dataIndex: 'id',
            fixed: 'right',
            width: FIXED_COLUMN_WIDTH,
            render: text => <a data-id={text} onClick={this.onDeleteDetail}>{formatMessage({
                id: 'newPanel.validation.delete',
                defaultMessage: '删除'
            })}</a>
        }];
        return (
            <div className="form-standard">
                <Spin spinning={this.state.loading}>
                    <Card title={formatMessage({
                        id: 'newPanel.column.common',
                        defaultMessage: '发运单信息'
                    })}>
                        <Form>
                            <Row>
                                <Col {...FORM_OPTIONS.col}>
                                    <Form.Item label={formatMessage({
                                        id: 'newPanel.operation.code',
                                        defaultMessage: '出运单号'
                                    })} {...FORM_OPTIONS.item}>
                                        {data.code}
                                    </Form.Item>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <Form.Item label={formatMessage({
                                        id: 'newPanel.operation.dealerId',
                                        defaultMessage: '总代'
                                    })} {...FORM_OPTIONS.item}>
                                        {`(${data.dealerCode})${data.dealerName}`}
                                    </Form.Item>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <Form.Item label={formatMessage({
                                        id: 'newPanel.operation.brandId',
                                        defaultMessage: '品牌'
                                    })} {...FORM_OPTIONS.item}>
                                        {`(${data.brandCode})${data.brandName}`}
                                    </Form.Item>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <Form.Item label={formatMessage({
                                        id: 'newPanel.operation.country',
                                        defaultMessage: '国家'
                                    })} {...FORM_OPTIONS.item}>
                                        {data.country}
                                    </Form.Item>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <Form.Item
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.form.boardDate',
                                            defaultMessage: '装船日期'
                                        })}
                                        {...FORM_OPTIONS.item}
                                        validateStatus={validateBoardDate}
                                        required>
                                        <WrappedDatePicker
                                            name="boardDate"
                                            value={data.boardDate}
                                            onChange={this.onChange}/>
                                    </Form.Item>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <Form.Item label={formatMessage({
                                        id: 'newPanel.operation.boardPort',
                                        defaultMessage: '装船港口'
                                    })} {...FORM_OPTIONS.item}
                                    validateStatus={validateBoardPort}
                                    required>
                                        <TextInput
                                            name="boardPort"
                                            value={data.boardPort}
                                            onBlur={this.onChange} />
                                    </Form.Item>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <Form.Item label={formatMessage({
                                        id: 'newPanel.operation.destinationPort',
                                        defaultMessage: '目的港口'
                                    })} {...FORM_OPTIONS.item}
                                    validateStatus={validateDestinationPort}
                                    required>
                                        <TextInput
                                            name="destinationPort"
                                            value={data.destinationPort}
                                            onBlur={this.onChange} />
                                    </Form.Item>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <Form.Item label={formatMessage({
                                        id: 'newPanel.operation.documentationClerkNo',
                                        defaultMessage: '单证员号'
                                    })} {...FORM_OPTIONS.item}>
                                        <TextInput
                                            name="documentationClerkNo"
                                            value={data.documentationClerkNo}
                                            onBlur={this.onChange} />
                                    </Form.Item>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <Form.Item label={formatMessage({
                                        id: 'newPanel.operation.carrierName',
                                        defaultMessage: '承运人'
                                    })} {...FORM_OPTIONS.item}
                                    validateStatus={validateCarrierName}
                                    required>
                                        <TextInput
                                            name="carrierName"
                                            value={data.carrierName}
                                            onBlur={this.onChange} />
                                    </Form.Item>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <Form.Item
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.form.planArriveTime',
                                            defaultMessage: '预计到达时间'
                                        })}
                                        {...FORM_OPTIONS.item}
                                        validateStatus={validatePlanArriveTime}
                                        required>
                                        <WrappedDatePicker
                                            name="planArriveTime"
                                            value={data.planArriveTime}
                                            onChange={this.onChange}/>
                                    </Form.Item>
                                </Col>
                            </Row>
                        </Form>
                    </Card>
                    <Card
                        title={formatMessage({
                            id: 'newPanel.operation.detail',
                            defaultMessage: '出运单清单'
                        })}
                        extra={<div>
                            <Button
                                size="small"
                                onClick={this.onClickAddDetailBtn}>
                                {formatMessage({
                                    id: 'newPanel.btn.add',
                                    defaultMessage: '增加清单'
                                })}
                            </Button>
                        </div>}>
                        <Table
                            className="white-space-nowrap"
                            columns={colums}
                            rowKey="id"
                            pagination={false}
                            dataSource={details}
                            {...TABLE} />
                    </Card>
                    <Card className={styles.optionBtn}>
                        <Button
                            type="primary"
                            onClick={this.onSubmit}
                            disabled={!submitable}
                            loading={loading}>
                            {formatMessage({
                                id: 'newPanel.operation.onSave',
                                defaultMessage: '保存'
                            })}
                        </Button>
                    </Card>
                    {
                        this.state.showSaleShipmentSelectPanel && <SaleShipmentSelectPanel
                            dealerId={data.id}
                            brandId={data.brandId}
                            selectKey={details.id}
                            onCancel={this.onClickAddDetailBtn}
                            onSelect={this.onSelectSaleShipmentLists} />
                    }
                </Spin>
                <div className="page-toolbar">
                    <Return
                        disabled={this.state.loading}
                        onConfirm={this.onClickOkOnPopconfirm}
                        showWarning={this.state.hasOperat} />
                </div>
            </div>
        );
    }
}

NewPanel.propTypes = {
    permissions: PropTypes.array.isRequired,
    successReturn: PropTypes.func.isRequired,
    onCancel: PropTypes.func.isRequired,
    onSubmit: PropTypes.func.isRequired,
    enterprise: PropTypes.object,
    history: PropTypes.object,
    id: PropTypes.string,
    intl: PropTypes.object,
};

import {connect} from 'react-redux';
import {
    tableSearch,
    onSubmit
} from './actions';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
const getPermissions = selectorFactory(['page', 'domainData', 'permission', 'data']);
const mapStateToProps = state => ({permissions: getPermissions(state)});
const mapDispatchToProps = (dispatch, props) => ({
    onSubmit: data => dispatch(onSubmit(data)),
    successReturn: () => {
        dispatch(tableSearch());
        props.history.push(routes.query.url());
    },
    onCancel: () => {
        props.history.push(routes.query.url());
    },
});
export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(NewPanel));
